﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static LiWi.Shell;

namespace LiWi
{
    public partial class 螺旋插补 : Form
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        public WindowsAdapt adapt = new WindowsAdapt();


        #region
        IntPtr _handle { get { return Data.handle; } }
        bool isConnect { get { return Data.handle == (IntPtr)0 ? false : true; } }
        public bool axisFlag = false;             //轴状态

        public int[] axisList = { 0, 1, 2, 3 ,4};


        public int runmode;                     //1：相对/绝对
        public int movemode;                    //1：圆心/3点/椭圆+螺旋/椭圆+螺旋多圈/空间圆弧+螺旋
        public int rotate;                      //1：顺/逆：旋转方向




        #endregion

        public 螺旋插补()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            initValue();
            adapt.SetForm(this);
        }





        private void Form1_Load(object sender, EventArgs e)
        {


        }
        public void initValue()
        {
            //TODO

        }





        private void radrunMove1_CheckedChanged(object sender, EventArgs e)
        {
            runmode = 1;
            radMoveMode5.Visible = true;
        }

        private void radrunMove2_CheckedChanged(object sender, EventArgs e)
        {
            runmode = 2;
            radMoveMode5.Visible = false;
        }

        private void radMoveMode1_CheckedChanged(object sender, EventArgs e)
        {
            movemode = 1;
        }

        private void radMoveMode2_CheckedChanged(object sender, EventArgs e)
        {
            movemode = 2;
        }

        private void radMoveMode3_CheckedChanged(object sender, EventArgs e)
        {
            movemode = 3;
        }

        private void radMoveMode4_CheckedChanged(object sender, EventArgs e)
        {
            movemode = 4;
        }
        private void radMoveMode5_CheckedChanged(object sender, EventArgs e)
        {
            movemode = 5;
        }
        /// <summary>
        /// 坐标清零
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btnzero_Click(object sender, EventArgs e)
        {
            foreach (var item in axisList)
            {
                PMC_SetDpos(_handle, item, 0);
            }
        }



        public async Task axisStart()
        {
            try
            {

                //设置轴参数
                for (int i = 0; i < 5; i++)
                {
                    PMC_SetUnits(Data.handle, i, Convert.ToInt32(num_uint.Value));
                    PMC_SetSpeed(Data.handle,i, Convert.ToInt32(num_sp.Value));
                    PMC_SetAccel(Data.handle,i,Convert.ToInt32(num_accel.Value));
                    PMC_SetDecel(Data.handle,i,Convert.ToInt32(num_decel.Value));
                }
                    
                if (radrunMove1.Checked) runmode = 1;
                else if (radrunMove2.Checked) runmode = 2;
                if (radMoveMode1.Checked) movemode = 1;
                else if (radMoveMode2.Checked) movemode = 2;
                else if (radMoveMode3.Checked) movemode = 3;
                else if (radMoveMode4.Checked) movemode = 4;
                else if (radMoveMode5.Checked) movemode = 5;
                if (radRotate1.Checked) rotate = 1;
                else if (radRotate2.Checked) rotate = 2;

                float[] destlist = { Convert.ToSingle(destpos0.Text), Convert.ToSingle(destpos1.Text), Convert.ToSingle(destpos2.Text), Convert.ToSingle(destpos3.Text), Convert.ToSingle(destpos4.Text) };
                float[] midlist = { Convert.ToSingle(txtmidPos0.Text), Convert.ToSingle(txtmidPos1.Text),Convert.ToSingle(txtmidPos2.Text) };
                float[] radcir = { Convert.ToSingle(radcir1.Text), Convert.ToSingle(radcir2.Text) };
                float gonum=Convert.ToSingle(txtgoNum.Text);
                int idirection=radRotate1.Checked ? 1 : 0;      //顺逆
                int velcalcul = chkOpen.Checked ? 0 : 1;      //开启速度计算1
                int model=Convert.ToInt32(commodel.Text);

                

                var ret = 0;
                axisFlag = true;
                Btnstart.Enabled = false;
                Btnstart.Text = "运动中";

                //起始点
                float[] startposlis = new float[axisList.Length];
                foreach (var item in axisList)
                {
                    float a = 0;
                    PMC_GetDpos(_handle, item, ref a);
                    startposlis[item] = a;
                }

                //判断缓冲剩余量:如果缓冲小于20等待一下               
                await Task.Run(() =>
                {
                    while (Data.ReMainBuffer(axisList) <= 20)
                    {
                        Thread.Sleep(200);
                    }

                    if (runmode == 1)           //相对
                    {
                        switch (movemode)
                        {

                            case 1:             //圆心螺旋插补    (句柄，轴数，轴列表，第一轴运动坐标，第二轴运动坐标，第一轴圆心，第二轴圆心，顺逆，第三轴运动距离，速度计算)


                                ret = PMC_MHelical(_handle, 3, axisList, destlist[0], destlist[1], midlist[0], midlist[1], idirection, destlist[2], velcalcul)
    ;
                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 2:         //3点画螺旋插补       (句柄，轴数，轴列表，第一轴中点，第二轴中点，第一轴结束，第二轴结束，第三轴运动距离，速度计算)

                                ret = PMC_MHelical2(_handle, 3, axisList, midlist[0], midlist[1], destlist[0], destlist[1], destlist[2], velcalcul);
                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 3:         //椭圆+螺旋插补       (句柄，轴数，轴列表，第一轴终点，第二轴终点，第一轴中心，第二轴中心，顺逆，第一轴椭圆半径，第二轴椭圆半径，第三轴移动距离)

                                ret = PMC_MEclipseHelical(_handle, 3, axisList, destlist[0], destlist[1], midlist[0], midlist[1], idirection, radcir[0], radcir[1], destlist[2]);

                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 4:         //椭圆+螺旋多圈插补     (句柄，轴数，轴列表，第一轴中心，第二轴中心，顺逆，第一轴椭圆半径，第二轴椭圆半径，圈数，第三轴运动距离，第三轴速度计算)

                                ret = PMC_Tangle(_handle, 3, axisList, midlist[0], midlist[1], idirection, midlist[0], midlist[1], gonum, destlist[2], velcalcul);
                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 5:         //空间圆弧+螺旋插补     (句柄，轴数，轴列表，第一轴运动距离1，第二轴运动距离1，第三轴运动距离1，第一轴运动距离2，第二轴运动距离2，第三轴运动距离2，模式，第4轴运动距离，第5轴运动距离)
                                ret = PMC_MSpherical(_handle, 5, axisList, destlist[0], destlist[1], destlist[2], midlist[0], midlist[1], midlist[2], model, destlist[3], destlist[4]);

                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                        }
                    }
                    else if (runmode == 2)      //绝对
                    {
                        switch (movemode)
                        {
                            case 1:             //圆心螺旋插补    (句柄，轴数，轴列表，第一轴运动坐标，第二轴运动坐标，第一轴圆心，第二轴圆心，顺逆，第三轴运动距离，速度计算)

                                ret = PMC_MHelicalAbs(_handle, 3, axisList, destlist[0], destlist[1], midlist[0], midlist[1], idirection, destlist[2], velcalcul)
    ;
                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 2:         //3点画螺旋插补       (句柄，轴数，轴列表，第一轴中点，第二轴中点，第一轴结束，第二轴结束，第三轴运动距离，速度计算)

                                ret = PMC_MHelical2Abs(_handle, 3, axisList, midlist[0], midlist[1], destlist[0], destlist[1], destlist[2], velcalcul);
                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 3:         //椭圆+螺旋插补       (句柄，轴数，轴列表，第一轴终点，第二轴终点，第一轴中心，第二轴中心，顺逆，第一轴椭圆半径，第二轴椭圆半径，第三轴移动距离)

                                ret = PMC_MEclipseHelicalAbs(_handle, 3, axisList, destlist[0], destlist[1], midlist[0], midlist[1], idirection, radcir[0], radcir[1], destlist[2]);

                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                            case 4:         //椭圆+螺旋多圈插补     (句柄，轴数，轴列表，第一轴中心，第二轴中心，顺逆，第一轴椭圆半径，第二轴椭圆半径，圈数，第三轴运动距离，第三轴速度计算)

                                ret = PMC_TangleAbs(_handle, 3, axisList, midlist[0], midlist[1], idirection, midlist[0], midlist[1], gonum, destlist[2], velcalcul);
                                if (ret != 0)
                                {
                                    Btnstart.Enabled = true;
                                    Btnstart.Text = "启 动";
                                    axisFlag = false;
                                    MessageBox.Show("启动失败");
                                    return;
                                }
                                break;
                        }
                    }
                });
                Thread thsport = new Thread(() =>
                {
                    foreach (var item in axisList)
                    {
                        var a = 0;
                        PMC_GetIfIdle(_handle, item, ref a);
                        while (a == 0)
                        {
                            PMC_GetIfIdle(_handle, item, ref a);
                            Thread.Sleep(50);
                        }
                    }
                    axisFlag = false;
                    Btnstart.Enabled = true;
                    Btnstart.Text = "启 动";


                }
                );
                thsport.Start();


            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                Btnstart.Enabled = true;
                Btnstart.Text = "启 动";
                axisFlag = false;
            }
        }



        private async void Btnstart_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < 5; ++i)
            {
                int enable = 0;
                PMC_GetAxisEnable(_handle, i, ref enable);
                if (enable == 0)
                {
                    MessageBox.Show("请回连接处将5个轴使能！！！");
                    return;
                }
            }
            PMC_Rapidstop(_handle, 3);
            Data._pause = false;
            if (isConnect) await axisStart();
            else MessageBox.Show("请先连接控制器！！！");

        }

        private void Move_FormClosing(object sender, FormClosingEventArgs e)
        {
            cts.Cancel();
        }

        private void BtnConnect_Click(object sender, EventArgs e)
        {
            //TODO
            //string _ip = "192.168.1.11";
            //int ret = PMC_OpenEth(_ip, ref _handle);
            //if (ret == 0)
            //{
            //    isConnect = true;
            //    MessageBox.Show("连接成功");
            //    getPos();

            //}
        }

        private void Btnstop_Click(object sender, EventArgs e)
        {
            if (axisFlag)
            {
                foreach (var item in axisList)
                {
                    PMC_Rapidstop(_handle, 3);
                }
                Data._pause = false;
            }
        }

        private void radRotate1_CheckedChanged(object sender, EventArgs e)
        {
            rotate = 1;
        }

        private void radRotate2_CheckedChanged(object sender, EventArgs e)
        {
            rotate = 2;
        }

        private void btn_pause_Click(object sender, EventArgs e)
        {
            if (!Data._pause)
            {
                PMC_MovePause(Data.handle, 0, 0);
                btn_pause.Text = "恢 复";
                Data._pause = true;
            }
            else
            {
                PMC_MoveResume(Data.handle, 0);
                btn_pause.Text = "暂 停";
                Data._pause = false;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Data._pause) Btnstart.Enabled = false;
            //else Btnstart.Enabled = true;
        }
    }


}






